package com.wcx.imitationwechatbilllist;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @param
 * @return
 * @author 魏
 * @time 2025/9/29 14:40
 */
public class MainActivity extends AppCompatActivity {

    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private BillAdapter adapter;
    private List<BillItem> items = new ArrayList<>();
    private int pageNum;
    private int month = 9;
    private RefreshFooter refresh_footer;
    private boolean flag = false;
    private TextView text_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text_view = findViewById(R.id.text_view);
        refreshLayout = findViewById(R.id.refresh_layout);
        recyclerView = findViewById(R.id.recycler_view);
        refresh_footer = findViewById(R.id.refresh_footer);

        // 设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        // 初始化适配器
        adapter = new BillAdapter(MainActivity.this,items);
        recyclerView.setAdapter(adapter);

        new Handler().postDelayed(()->{
            int height = text_view.getHeight();
            StickyHeaderDecoration decoration = new StickyHeaderDecoration(adapter);
            // 添加粘性头部装饰器
            recyclerView.addItemDecoration(decoration);
            // 添加触摸事件监听器
            recyclerView.addOnItemTouchListener(
                    new StickyHeaderTouchListener(this, recyclerView, decoration,height));
        },100);

        pageNum=1;
        month = 10;
        requestData(true);

        // 设置刷新头部和底部
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));

        refreshLayout.setOnRefreshListener(refreshlayout -> {
            pageNum=1;
            month = 10;
            requestData(true);

        });


        // 上拉加载更多监听
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("++++++++++","底部1");
                if (!recyclerView.canScrollVertically(1)) {
                    Log.d("++++++++++","已经滚动到底部1");
                }

                View lastChildView = recyclerView.getLayoutManager().getChildAt(
                        recyclerView.getLayoutManager().getChildCount() - 1);

                if (lastChildView != null) {
                    int lastChildBottom = lastChildView.getBottom();
                    int recyclerBottom = recyclerView.getBottom() - recyclerView.getPaddingBottom();
                    int lastPosition = recyclerView.getLayoutManager().getPosition(lastChildView);
                    int itemCount = recyclerView.getLayoutManager().getItemCount();

                    if (lastChildBottom == recyclerBottom && lastPosition == itemCount - 1) {
                        // 精确判断已经滚动到底部
                        Log.d("++++++++++", "精确判断已经滚动到底部3");
                        refresh_footer.loading();
                        refresh_footer.setVisibility(View.VISIBLE);
                        pageNum++;
                        requestData(false);
                    }else {
                        Log.d("++++++++++", "到底了");
                    }
                }

            }
        });

    }

    private void requestData(boolean isRefresh) {
        List<BillItem> newItems = generateTestData();
        // 模拟网络请求延迟
        new Handler(Looper.myLooper()).postDelayed(() -> {
            refresh_footer.loadedSuccessfully();
            new Handler(Looper.myLooper()).post(new Runnable() {
                @Override
                public void run() {
                    refresh_footer.setVisibility(View.GONE);
                }
            });
            if (isRefresh) {
                // 修改前（过时）
                //adapter.setNewData(newItems);
                // 修改后（推荐）
                adapter.setList(newItems); // 适用于 3.x 版本;依赖：implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4' // 请确认此处的版本号
                //adapter.submitList(newItems);//（适用于 4.x及以上）
                refreshLayout.finishRefresh();
                refreshLayout.finishRefresh();
            } else {
                if (pageNum >= 6) { // 模拟没有更多数据
                    pageNum--;
                    refreshLayout.finishLoadMoreWithNoMoreData();
                    refresh_footer.noMoreDataAvailable();
                } else {
                    adapter.addData(newItems);
                    refreshLayout.finishLoadMore();
                }
            }
        }, 1500);

    }

    private List<BillItem> generateTestData() {
        List<BillItem> item = new ArrayList<>();
        List<ItemBean> list = new ArrayList<>();
        // 添加账单数据
        for (int i = 1; i <= 10; i++) {
            boolean isIncome = i % 3 == 0;
            String amount = (isIncome ? "+" : "-") + (i * 100) + "元";
            list.add(new ItemBean(month + "月" + i + "日",
                    "消费项目" + i, amount, isIncome));
        }
        // 添加月份标题
        if (month==9){
            if (flag){
                item.add(new BillItem("2023年" + month + "月", false,list));
                flag = false;
                month--;
            }else {
                item.add(new BillItem("2023年" + month + "月", true,list));
                flag = true;
            }
        }else {
            // 添加月份标题
            item.add(new BillItem("2023年" + month + "月", true,list));
            month--;
            Log.d("++++++++++m", "其他月份添加");
        }
        return item;
    }
}